import os
import shutil
from datetime import datetime
from typing import Union, Optional, Any, List, Dict

import pytz as pytz
import redis
from fastapi_amis_admin.models import Field
from pydantic import BaseModel
from fastapi import HTTPException, Depends
from sqlmodel import SQLModel

from backend.core.app_redis import app_redis
from backend.core.settings import settings

tz = pytz.timezone('Asia/Shanghai')

cache = redis.Redis(host=settings.redis_host,
                  port=settings.redis_port,
                  password=settings.redis_password,
                  db=settings.redis_db)

# cache = app_redis(host=settings.redis_host,
#                   port=settings.redis_port,
#                   password=settings.redis_password,
#                   db=settings.redis_db)

class PageParams(BaseModel):
    page: Optional[int] = Field(default=1, title="页码", description="页码")
    size: Optional[int] = Field(default=10, title="每页条数", description="每页条数")


class PageResult(BaseModel):
    page: Optional[int] = Field(default=1, title="页码", description="页码")
    size: Optional[int] = Field(default=10, title="每页条数", description="每页条数")
    total: Optional[int] = Field(default=0, title="总数", description="总数")
    list: Optional[List] = Field(default=None, title="页码", description="分页数据列表")


class ApiResult(BaseModel):
    code: Optional[int] = Field(default=200, description="状态码")
    msg: Optional[str] = Field(default="", description="错误描述")
    data: Optional[Any] = Field(default=None, description="数据")



class AppException(HTTPException):
    def __init__(self, err_code: int = 400, err_msg: str = ''):
        self.status_code = 200
        self.detail = ''
        self.err_code = err_code
        self.err_msg = err_msg

class AppBaseModel(SQLModel):
    id: Optional[int] = Field(primary_key=True, title='id', exclude=False)
    creator: Optional[int] = Field(title='创建者', exclude=True)
    create_date: Optional[datetime] = Field(index=True, title='创建时间', exclude=True,
                                            serialization_alias="createDate", validation_alias="createDate", alias="createDate")
    updater: Optional[int] = Field(title='更新者', exclude=True)
    update_date: Optional[datetime] = Field(title='更新时间', exclude=True,
                                            serialization_alias="updateDate", validation_alias="updateDate",alias="updateDate")
    deleted: Optional[int] = Field(default=0, title="删除标记", description='0:使用  1:删除', exclude=True)

    class Config:
        orm_mode = True

class CommonUtil:
    def add_common_field_set(data: AppBaseModel, userId: int):
        data.creator = userId
        data.create_date = datetime.now(tz)
        data.updater = userId
        data.update_date = datetime.now(tz)
        data.deleted = 0

    def update_common_field_set(data: AppBaseModel, userId: int):
        data.updater = userId
        data.update_date = datetime.now(tz)

    def tuple_to_model(item: tuple, BaseModel):
        params = dict()
        index = 0
        for k in BaseModel.model_fields:
            if not k.startswith('_'):
                params[k] = item[index]
                index += 1
        return BaseModel(**params)

    def list_tuple_to_model(items: [], BaseModel):
        list = []
        for item in items:
            m = CommonUtil.tuple_to_model(item, BaseModel)
            list.append(m)
        return list


    def get_file_extension(file_path):
        return os.path.splitext(file_path)[-1]

    # 创建一个新的文件夹
    def create_directory(path):
        if not os.path.exists(path):
            os.makedirs(path)
            print(f"Directory '{path}' created successfully")
        else:
            print(f"Directory '{path}' already exists")

    # 删除一个文件夹及其所有内容
    def delete_directory(path):
        if os.path.exists(path):
            shutil.rmtree(path)
            print(f"Directory '{path}' and its contents deleted successfully")
        else:
            print(f"Directory '{path}' does not exist")